<template>
  <!-- 面包屑导航区域 -->
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索区域 -->
      <el-form :model="search">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-input
              placeholder="用户名搜索"
              v-model="search.username"
              prefix-icon="el-icon-search"
            ></el-input>
          </el-col>
          <el-col :span="4">
            <el-input
              placeholder="姓名搜索"
              v-model="search.name"
              prefix-icon="el-icon-search"
            ></el-input>
          </el-col>
          <el-col :span="3">
            <el-select v-model="search.value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="search.value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 250px"
            >
            </el-date-picker>
          </el-col>

          <!-- 增删查按钮区域 -->
          <el-col :span="4">
            <el-tooltip
              class="item"
              effect="light"
              content="添加用户"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit-outline"
                circle
                @click="addDialogFormVisible = true"
              >
              </el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="light"
              content="查找用户"
              placement="top"
            >
              <el-button
                icon="el-icon-search"
                circle
                @click="searchlist()"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="userListDelete"
              ></el-button>
            </el-tooltip>
          </el-col>
          <!-- 上载导出功能 -->
          <el-col :span="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8081/users/readexcl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              multiple
              :limit="3"
              :file-list="fileList"
              :on-change="upload"
              :show-file-list="false"
              style="display: inline-block"
            >
              <el-tooltip
                class="item"
                effect="light"
                content="上载表格"
                placement="top"
              >
                <el-button
                  type="primary"
                  circle
                  icon="el-icon-upload2"
                ></el-button>
              </el-tooltip>
            </el-upload>
            <el-tooltip
              class="item"
              effect="dark"
              content="导出表格"
              placement="top"
            >
              <el-button
                type="warning"
                circle
                icon="el-icon-download"
                @click="download"
              >
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form>
      <!-- 用户列表区域 -->
      <div class="usertable">
        <el-table
          :data="userlist"
          border
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="60"
            :filtered-value="true"
            header-align="center"
            align="center"
          >
          </el-table-column>
          <el-table-column type="index" width="60" label="序号">
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="150">
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="120">
          </el-table-column>
          <el-table-column
            prop="sex"
            label="性别"
            width="120"
            :formatter="turnsex"
          >
          </el-table-column>
          <el-table-column prop="tele" label="电话" width="120">
          </el-table-column>
          <el-table-column prop="emil" label="邮箱地址" width="200">
          </el-table-column>
          <el-table-column prop="maketime" label="创建时间" width="120">
            <!-- <el-date-picker  v-model="maketime"  type="date" readonly>
            </el-date-picker> -->
          </el-table-column>
          <el-table-column
            prop="lastdatechange"
            label="最后修改时间"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="stat"
            label="状态"
            width="100"
            :formatter="turnstat"
          >
            <template slot-scope="scope">
              <el-switch
                active-value="1"
                inactive-value="0"
                v-model="scope.row.stat"
                @change="edituserstat(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="190">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="light"
                content="修改用户"
                placement="top"
              >
                <el-button
                  @click="showEditDialog(scope.row)"
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  plain
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="light"
                content="删除用户"
                placement="top"
              >
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  plain
                  @click="userDelete(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="light"
                content="设置角色"
                placement="top"
              >
                <el-button
                  @click="openPart(scope.row)"
                  type="warning"
                  size="small"
                  icon="el-icon-s-tools"
                  plain
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="pageSize"
            :current-page="currentPage"
            layout="sizes, prev, pager, next"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 增加用户对话框区域 -->
    <div>
      <el-dialog
        title="添加用户:"
        :visible.sync="addDialogFormVisible"
        class="dialog"
        @close="addDialogClosed()"
      >
        <el-form
          :model="adduserlist"
          :rules="adduserlistRules"
          ref="adduserlistRef"
          :label-position="labelPosition"
          label-width="90px"
          hide-required-asterisk
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="用户名:" prop="username">
                <el-input
                  v-model="adduserlist.username"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="姓名:" prop="name">
                <el-input
                  v-model="adduserlist.name"
                  autocomplete="off"
                ></el-input> </el-form-item
            ></el-col>
            <el-col span="10">
              <el-form-item label="密码:" prop="password">
                <el-input
                  v-model="adduserlist.password"
                  type="password"
                ></el-input> </el-form-item
            ></el-col>
            <el-col span="10">
              <el-form-item label="确认密码:" prop="passwordqr">
                <el-input
                  v-model="adduserlist.passwordqr"
                  type="password"
                ></el-input> </el-form-item
            ></el-col>

            <el-col :span="10">
              <el-form-item label="联系电话:" prop="tele">
                <el-input
                  v-model="adduserlist.tele"
                  autocomplete="off"
                ></el-input> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="邮箱:" prop="email">
                <el-input v-model="adduserlist.email"></el-input> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="性别:">
                <el-radio v-model="adduserlist.sex" label="0">男</el-radio>
                <el-radio v-model="adduserlist.sex" label="1">女</el-radio>
              </el-form-item></el-col
            >
            <el-col :span="10">
              <el-form-item label="状态:">
                <el-radio v-model="adduserlist.stat" label="1">有效</el-radio>
                <el-radio v-model="adduserlist.stat" label="0">无效</el-radio>
              </el-form-item></el-col
            >
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="adduser">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 修改用户对话框区域 -->
    <div>
      <el-dialog
        title="修改用户:"
        :visible.sync="editDialogFormVisible"
        class="dialog"
        @close="editDialogClosed()"
      >
        <el-form
          :model="edituserlist"
          :rules="edituserlistRules"
          ref="edituserlistRef"
          :label-position="labelPosition"
          label-width="90px"
          hide-required-asterisk
        >
          <el-form-item label="用户名:" prop="username">
            <el-input v-model="edituserlist.username"></el-input>
          </el-form-item>
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="edituserlist.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input
              v-model="edituserlist.password"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="passwordqr">
            <el-input
              v-model="edituserlist.passwordqr"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别:">
            <el-radio v-model="edituserlist.sex" :label="0">男</el-radio>
            <el-radio v-model="edituserlist.sex" :label="1">女</el-radio>
          </el-form-item>
          <el-form-item label="联系电话:" prop="tele">
            <el-input v-model="edituserlist.tele" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="emil">
            <el-input v-model="edituserlist.emil"></el-input>
          </el-form-item>
          <el-form-item label="状态:">
            <el-radio v-model="edituserlist.stat" label="1">有效</el-radio>
            <el-radio v-model="edituserlist.stat" label="0">无效</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="edituser">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 设置用户区域 -->
    <div>
      <el-dialog
        title="设置用户:"
        :visible.sync="partVisible"
        class="dialog"
        width="750px"
      >
        <el-table
          :data="partList"
          ref="multipleTable"
          border
          style="width: 100%"
          :header-cell-style="{ 'text-align': 'center' }"
          @selection-change="handleSelectionChangePartList"
        >
          <el-table-column
            type="selection"
            width="60"
            header-align="center"
            align="center"
          ></el-table-column>
          <el-table-column prop="code" label="角色编码" width="160">
          </el-table-column>
          <el-table-column prop="name" label="角色名称" width="160">
          </el-table-column>
          <el-table-column prop="startime" label="生效日期" width="165">
          </el-table-column>
          <el-table-column prop="downtime" label="失效日期" width="164">
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="partVisible = false">取 消</el-button>
          <el-button @click="listgavepower" type="primary">确 认</el-button>
        </div>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="partquery.size"
            :current-page="partquery.ipage"
            layout="sizes, prev, pager, next"
            :total="parttotal"
          >
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
</template>



<script>
// const sexType = [
//   { type: "0", name: "男" },
//   { type: "0", name: "女" },
// ];
// const statusType = [
//   { type: "0", name: "有效" },
//   { type: "1", name: "无效" },
// ];
export default {
  data() {
    //自定义校验规则
    var validateUsername = (rule, value, callback) => {
      var reg = new RegExp(/^[A-Za-z\u4E00-\u9FA5]{6,20}$/); //字符串正则表达式 6到20位（字母，数字，下划线，减号）
      if (value == "") {
        callback(new Error("请输入用户名"));
      } else if (!reg.test(value)) {
        callback(new Error("用户名格式不正确"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.adduserlist.passwordqr !== "") {
          this.$refs.adduserlistRef.validateField("passwordqr");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.adduserlist.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.edituserlist.passwordqr !== "") {
          this.$refs.edituserlistRef.validateField("passwordqr");
        }
        callback();
      }
    };
    var validatePass4 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.edituserlist.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      //设置角色表格
      partVisible: false,
      partList: [],
      userid: 0,
      //权限
      partquery: {
        name: "",
        status: "",
        ipage: 0,
        size: 5,
      },
      parttotal: 0,
      //多选框选中的角色
      partListSelect: [],
      //多选款默认选中的角色
      partListSS: [],
      search: {
        username: "",
        name: "",
        value: "",
      },
      options: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "1",
          label: "有效",
        },
        {
          value: "0",
          label: "无效",
        },
      ],
      value1: [new Date(2000, 0, 0), new Date(2022, 1, 1)],
      //用户表格数据
      userlist: [],
      pageSize: 5,
      currentPage: 1,
      total: 0,
      //用户列表多选选中框的值
      idList: [],
      //DIALOG弹出框
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      //添加用户数据
      labelPosition: "right",
      adduserlist: {
        username: "",
        name: "",
        password: "",
        passwordqr: "",
        sex: "",
        tele: "",
        email: "",
        stat: "",
      },
      //修改用户数据
      edituserlist: {
        // id: null,
        // username: "",
        // name: "",
        // password: "",
        // passwordqr: "",
        // sex: "",
        // tele: "",
        // email: "",
        // stat: "",
      },
      //添加用户校验规则
      adduserlistRules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            pattern: /^[A-Za-z\u4E00-\u9FA5]{2,50}$/,
            message: "请输入由字母汉字组成且长度2-50位的姓名",
            trigger: "blur",
          },
        ],
        password: [{ validator: validatePass, trigger: "blur" }],
        passwordqr: [{ validator: validatePass2, trigger: "blur" }],
        tele: [
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            message: "请输入正确格式的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: false, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
        stat: [{ required: true }],
      },
      //修改用户数据校验规则
      edituserlistRules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            pattern: /^[A-Za-z\u4E00-\u9FA5]{2,50}$/,
            message: "请输入由字母汉字组成且长度2-50位的姓名",
            trigger: "blur",
          },
        ],
        password: [{ validator: validatePass3, trigger: "blur" }],
        passwordqr: [{ validator: validatePass4, trigger: "blur" }],
        tele: [
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            message: "请输入正确格式的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: false, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
        ],
        stat: [{ required: true }],
      },
      //导出
      fileList: [],

      //角色多选
      selecList: [],
    };
  },
  created() {
    this.searchlist();
  },
  methods: {
    //获取权限列表
    openPart(row) {
      this.$axios
        .get("/part/selepart", {
          params: this.partquery,
        })
        .then((res) => {
          console.log(res);
          this.partList = res.data.res.records;
          //console.log(this.partList);
          this.parttotal = res.data.res.total;
          this.userid = row.id;
          //获取已勾选的多选框ID
          this.$axios.post("/users/part", row.id).then((res) => {
           // console.log(res);
           // console.log(row.id)
            this.selecList = res.data.res;
          });
          this.partVisible = !this.partVisible;
          //设置多选框状态
          let list = [];
          this.partList.forEach((item) => {
            this.selecList.forEach((el) => {
              if (el === item.id) {
                list.push(item);
              }
            });
          });
          if (list) {
            this.$nextTick(() => {
              list.forEach((row) => {
                console.log(list);
                // this.$refs.multipleTable.clearSelection();
                this.$refs.multipleTable.toggleRowSelection(row, true);
              });
            });
          }
        });
    },
    //批量设置角色
    handleSelectionChangePartList(val) {
      this.partListSelect = val;
    },
    listgavepower() {
      let checkArr = this.partListSelect;
      let powerparams = [];
      checkArr.forEach(function (item) {
        //console.log(item)
        powerparams.push(item.id); //添加所有需要数据的id到数组
      });
      let querylistpower = {
        partId: powerparams,
        userid: this.userid,
      };
      //console.log(querylistpower);
      this.$axios.post("/users/gavePart", querylistpower).then((res) => {
        console.log(res);
        if (res.status == 200) {
          this.$message.success("批量设置角色成功");
          this.partVisible = !this.partVisible;
        }
      });
    },

    //保持角色多选状态
    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach((row) => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },

    //获取用户列表
    searchlist() {
      this.$axios
        .get("/users/select", {
          params: {
            username: this.search.username,
            name: this.search.password,
            stat: this.search.value,
            size: this.pageSize,
            ipage: this.currentPage,
          },
        })
        .then((res) => {
          console.log(res);
          this.userlist = res.data.res.records;
          this.total = res.data.res.total;
        });
    },
    //转换数据为性别
    turnsex(row, index) {
      if (row.sex == "0") {
        return "男";
      } else if (row.sex == "1") {
        return "女";
      }
    },
    //转换状态类型
    turnstat(row, index) {
      if (row.stat == "0") {
        return "无效";
      } else if (row.stat == "1") {
        return "有效";
      }
    },
    //监听 pagesize改变
    handleSizeChange(newSize) {
      this.currentPage = 1;
      this.pageSize = newSize;
      this.searchlist();
    },
    handleSizeChange2(newSize) {
      this.partquery.ipage = 1;
      this.partquery.size = newSize;
      this.openPart();
    },
    //监听 页码改变
    handleCurrentChange(newCurrent) {
      this.currentPage = newCurrent;
      this.searchlist();
    },
    handleCurrentChange2(newCurrent) {
      this.partquery.ipage = newCurrent;
      this.openPart();
    },
    //监听对话框关闭并且清除数据
    addDialogClosed() {
      this.$refs.adduserlistRef.resetFields();
    },
    //添加用户
    adduser() {
      this.$refs.adduserlistRef.validate((valid) => {
        if (!valid) return;
        this.$axios.post("/users/add", this.adduserlist).then((res) => {
          if (res.status == 200) {
            console.log(res);
            this.searchlist();
            this.$message.success("添加用户成功");
          } else {
            this.$message.error("添加用户失败");
          }
        });
        this.addDialogFormVisible = false;
      });
    },
    //监听修改对话框关闭并且清除数据
    editDialogClosed() {
      this.edituserlist = [];
      // this.$refs.edituserlistRef.resetFields();
    },
    //获取修改用户对应数据
    showEditDialog(row) {
      this.editDialogFormVisible = true;
      console.log(row);
      this.edituserlist = row;
      //this.adduserlist = scope.row;
    },
    //修改用户
    edituser() {
      this.$refs.edituserlistRef.validate((valid) => {
        console.log(valid);
        if (!valid) return;
        this.$axios.post("/users/update", this.edituserlist).then((res) => {
          console.log(res);
          if (res.status == 200) {
            this.$message.success("修改用户信息成功");
            this.searchlist();
          } else {
            this.$message.error("修改用户信息失败");
          }
        });
        this.editDialogFormVisible = false;
      });
    },
    //修改用户状态
    edituserstat(row) {
      this.$axios.post("/users/update", row).then((res) => {
        //console.log(res);
        if (res.status == 200) {
          this.$message.success("修改用户状态成功");
          this.searchlist();
          //console.log(row.stat)
        } else {
          this.$message.error("修改用户状态失败");
        }
      });
    },
    //获取多选的数据
    handleSelectionChange(val) {
      this.idList = val;
      console.log(val);
    },
    //用户批量删除
    userListDelete() {
      let checkArr = this.idList;
      let params = [];
      checkArr.forEach(function (item) {
        //console.log(item)
        params.push(item.id); //添加所有需要删除数据的id到paramas数组
      });
      //console.log(params);
      this.$confirm("此操作将永久删除用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.post("/users/deleliset", params).then((res) => {
            this.searchlist();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //用户删除
    userDelete(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.$axios.get("/users/dele?id=" + id).then((res) => {
            this.searchlist();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //上传功能
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // //上载表格
    // importExcel(file) {
    //   // let file = file.files[0] // 使用传统的input方法需要加上这一步
    //   const types = file.name.split(".")[1];
    //   const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
    //     (item) => item === types
    //   );
    //   if (!fileType) {
    //     alert("格式错误！请重新选择");
    //     return;
    //   }
    //   this.file2Xce(file).then((tabJson) => {
    //     if (tabJson && tabJson.length > 0) {
    //       this.xlsxJson = tabJson;
    //       // xlsxJson就是解析出来的json数据,数据格式如下
    //       // [
    //       //   {
    //       //     sheetName: sheet1
    //       //     sheet: sheetData
    //       //   }
    //       // ]
    //     }
    //   });
    // },
    // //上传
    upload(res) {
      console.log(res);
    },
    //导出功能
    download() {
      window.open(
        "http://localhost:8081/users/download?name=" +
          this.search.name +
          "&username=" +
          this.search.username +
          "&stat=" +
          this.search.value
      );
    },
  },
};
</script>

<style lang="less" scoped>
span {
  font-size: 12px;
}

.el-button {
  position: relative;
  margin-left: 10px;
}

.el-table-column {
  text-align: center;
}

.usertable {
  margin-top: 20px;
}

.block {
  margin-top: 20px;
}
</style>
